package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {


    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        // 1.校验
        dto.checkParam();
        // 2.封装查询条件
        IPage<ApUserRealname> pageRequest = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //查询全部,无状态
        if(dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        // 3.执行查询
        IPage<ApUserRealname> pageResult = this.page(pageRequest, wrapper);
        // 4.封装返回结果
        PageResponseResult pageResponseResult =
                new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());

        return pageResponseResult;
    }

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * 实名认证审核
     */

    //事务
    /*@GlobalTransactional*/
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Integer status) {
        // 1. 检查参数
        if(dto == null || dto.getId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据ID查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        if(userRealname == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 3. 判断实名认证状态是否为待审核
        if(userRealname.getStatus().intValue()!=1){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 4. 查询实名认证用户关联的ap_user信息
        ApUser apUser =(ApUser) apUserMapper.selectById(userRealname.getUserId());
        if(apUser == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"关联用户信息不存在");
        }
        // 5. 更新实名认证信息
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);

        // 6. 判断状态为9  生成自媒体账号/作者信息
        if(status.intValue() == AdminConstants.AD_USER_ISSTATUS){
            WmUser wmUser = createWmUser(dto,apUser);
            if(wmUser == null){
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"创建自媒体用户失败");
            }
            createAuthor(wmUser);
        }
        // 7. 当前用户为自媒体人
        apUser.setFlag((short)1);
        apUser.setIdentityAuthentication(true);
        apUserMapper.insert(apUser);
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 创建作者信息
     * @param wmUser
     */

    private ResponseResult createAuthor(WmUser wmUser) {
        ApAuthor author = articleFeign.findByUserId(wmUser.getApUserId());
        if(author!=null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"关联的作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(wmUser.getName());
        author.setType(2);
        author.setUserId(wmUser.getApUserId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        return articleFeign.save(author);
    }

    /**
     * 创建自媒体用户
     * @param dto
     * @param apUser
     * @return
     */

    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(AuthDto dto, ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if(wmUser!=null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"关联的自媒体用户已经存在");
        }
        //属性拷贝
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);

        //设置其他字段
        wmUser.setApUserId(apUser.getId());
        wmUser.setId(null);
        return wemediaFeign.save(wmUser);
    }
}
